package com.yanyilu.qiubite.service;

import com.yanyilu.qiubite.entity.Story;
import com.yanyilu.qiubite.jpa.PartJpa;
import com.yanyilu.qiubite.jpa.SpotJpa;
import com.yanyilu.qiubite.jpa.StoryJpa;
import com.yanyilu.qiubite.jpa.StorylineJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StoryService {
    @Autowired
    StoryJpa storyJpa;
    @Autowired
    SpotJpa spotJpa;
    @Autowired
    PartJpa partJpa;
    @Autowired
    StorylineJpa storylineJpa;

    public void addStory(Story story) {
        if(null == story.getSpotName()){
            String spotName = spotJpa.findSpotNameBySpotId(story.getSpotId());
            story.setSpotName(spotName);
        }
        storyJpa.save(story);
    }

    @Transactional
    public void deleteStory(Integer storyId) {
        List<Integer> partIds = partJpa.findPartIdByStoryId(storyId);
        storyJpa.deleteById(storyId);
        partJpa.deleteByStoryId(storyId);
        storylineJpa.deleteByPartIds(partIds);
    }

    public Page<Story> getList(Example<Story> example, Pageable pageable) {
        return storyJpa.findAll(example,pageable);
    }

    public Page<Story> getListByStoryIds(String storyName, Pageable pageable, Integer spotId) {
        if(null == spotId){
            spotId = 0;
        }
        return storyJpa.findByStoryIds(storyName,pageable,spotId);
    }
}
